<template>
  <div class="app-container">
    <el-tabs v-model="activeName"
             type="card"
             @tab-click="handleClick">
      <el-tab-pane label="销售中"
                   name="sale">
        <div class="filter-container">
          <el-select class="filter-item"
                     style="width: 150px;"
                     v-model="listQuery.category_id"
                     placeholder="类目"
                     filterable
                     clearable>
            <el-option
              v-for="item in varityList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
         
          <el-select class="filter-item"
                     style="width: 150px;"
                     v-model="listQuery.country_id"
                     placeholder="国家"
                     filterable
                     clearable>
            <el-option
              v-for="item in countryList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
            </el-option-group>
          </el-select>
          <el-input v-model="listQuery.keyword"
                    placeholder="输入关键词或ID搜索"
                    style="width: 200px;"
                    class="filter-item"
                    @keyup.enter.native="handleFilter" />
          <el-button 
                     class="filter-item"
                     type="primary"
                     icon="el-icon-search"
                     @click="handleFilter">
            查询
          </el-button>

        </div>
        <div class="add-brand">
          <el-button type="warning"
                     icon="el-icon-plus"
                     @click="$router.push({ path: '/product/productManager/create' })">添加产品</el-button>
          <el-button type="danger"
                     icon="el-icon-download"
                     disabled
                     v-if="!multipleSelectionSaleStatus">批量下架</el-button>
          <el-button type="danger"
                     icon="el-icon-download"
                     @click="takeOffProduct"
                     v-if="multipleSelectionSaleStatus">批量下架</el-button>
        </div>
        <el-table :key="tableKey"
                  ref="multipleTableSale"
                  v-loading="listLoading"
                  :data="list"
                  fit
                  highlight-current-row
                  style="width: 100%;"
                  @sort-change="sortChange"
                  @selection-change="handleSelectionChangeSale">
          <el-table-column type="selection"
                           width="55" />
          <el-table-column label="ID"
                           prop="product_id"
                           sortable="custom"
                           align="center"
                           width="80"
                           :class-name="getSortClass('id')">
            <template slot-scope="{row}">
              <span>{{ row.product_id }}</span>
            </template>
          </el-table-column>

          <el-table-column label="产品图片"
                           align="center"
                           prop="img"
                           min-width="100px">
            <template slot-scope="{row}">
              <img :src="formatImage(row.img)">
            </template>
          </el-table-column>
          <el-table-column label="产品名称"
                           prop="name"
                           min-width="200px">
            <template slot-scope="{row}">
              <a @click.stop="$router.push({ path: `/product/productManager/edit/${row.product_id}` })" class="a-hover">{{ row.name }}</a>
            </template>
          </el-table-column>
          <el-table-column label="原价"
                           align="center"
                           prop="origin_price"
                           min-width="100px">
            <template slot-scope="{row}">
              <span>{{ row.origin_price / 100 }}</span>
            </template>
          </el-table-column>
          <el-table-column label="特价"
                           align="center"
                           prop="special_price"
                           min-width="100px">
            <template slot-scope="{row}">
              <span>{{ row.special_price / 100 }}</span>
            </template>
          </el-table-column>
         
         
        

          <el-table-column label="状态"
                           prop="status"
                           class-name="status-col"
                           sortable="custom"
                           width="100">
            <template slot-scope="{row}">
              <!--  <el-tag :type="row.status | statusFilter">
            {{ row.status }}
          </el-tag> -->
              <span v-if="row.status==0"
                    class="status-ball draft" />
              <span v-if="row.status==1"
                    class="status-ball published" />
              <span>{{row.status | statusFilter}}</span>
              <!-- <span>{{ row.status }}</span> -->
            </template>
          </el-table-column>
          <el-table-column label="操作"
                           align="center"
                           width="230"
                           class-name="small-padding fixed-width">
            <template slot-scope="{row,$index}">

             <!--  <el-button v-if="row.status!=1"
                         size="mini"
                         type="success"
                         icon="el-icon-check"
                         @click="handleModifyStatus(row,1)" /> -->
              <el-button v-if="row.status!=0"
                         size="mini"
                         type="warning"
                         @click="handleModifyStatus(row,0)">
                下架
              </el-button>
              <el-button type="primary"
                         size="mini"
                         icon="el-icon-edit"
                         @click.stop="$router.push({ path: `/product/productManager/edit/${row.product_id}` })" />
              <!-- <el-button v-if="row.status!=1"
                         size="mini"
                         type="danger"
                         icon="el-icon-delete"
                         @click="handleDelete(row,$index)" /> -->
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total>0"
                    :total="total"
                    :page.sync="listQuery.page"
                    :limit.sync="listQuery.page_size"
                    @pagination="getList" />
      </el-tab-pane>
      <el-tab-pane label="仓库中"
                   name="store">
        <div class="filter-container">
          <el-select class="filter-item"
                     style="width: 150px;"
                     v-model="listQuery.category_id"
                     placeholder="类目"
                     filterable
                     clearable >
            <el-option
              v-for="item in varityList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
         
          <el-select class="filter-item"
                     style="width: 150px;"
                     v-model="listQuery.country_id"
                     placeholder="国家"
                     filterable
                     clearable >
            <el-option
              v-for="item in countryList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
          <el-input v-model="listQuery.keyword"
                    placeholder="输入关键词或ID搜索"
                    style="width: 200px;"
                    class="filter-item"
                    @keyup.enter.native="handleFilter" />
          <el-button 
                     class="filter-item"
                     type="primary"
                     icon="el-icon-search"
                     @click="handleFilter">
            查询
          </el-button>

        </div>
        <div class="add-brand">
          <el-button type="warning"
                     icon="el-icon-plus"
                     @click="$router.push({ path: '/product/productManager/create' })">添加产品</el-button>
          <el-button type="danger"
                     icon="el-icon-upload2"
                     disabled
                     v-if="!multipleSelectionStoreStatus">批量上架</el-button>
          <el-button type="danger"
                     icon="el-icon-upload2"
                     @click="takeOnProduct"
                     v-if="multipleSelectionStoreStatus">批量上架</el-button>
          <!-- <el-button type="warning" icon="el-icon-download" @click="takeOffProduct">批量下架</el-button> -->
        </div>
        <el-table :key="tableKey"
                  ref="multipleTableStore"
                  v-loading="listLoading"
                  :data="list"
                  fit
                  highlight-current-row
                  style="width: 100%;"
                  @sort-change="sortChange"
                  @selection-change="handleSelectionChangeStore">
          >
          <el-table-column type="selection"
                           width="55" />
          <el-table-column label="ID"
                           prop="product_id"
                           sortable="custom"
                           align="center"
                           width="80"
                           :class-name="getSortClass('id')">
            <template slot-scope="{row}">
              <span>{{ row.product_id }}</span>
            </template>
          </el-table-column>

          <el-table-column label="产品图片"
                           align="center"
                           prop="img"
                           min-width="100px">
            <template slot-scope="{row}">
              <img :src="formatImage(row.img)">
            </template>
          </el-table-column>
          <el-table-column label="产品名称"
                           prop="name"
                           min-width="200px">
            <template slot-scope="{row}">
              <a @click.stop="$router.push({ path: `/product/productManager/edit/${row.product_id}` })" class="a-hover">{{ row.name }}</a>
            </template>
          </el-table-column>
          <el-table-column label="原价"
                           align="center"
                           prop="origin_price"
                           min-width="100px">
            <template slot-scope="{row}">
              <span>{{ row.origin_price / 100 }}</span>
            </template>
          </el-table-column>
          <el-table-column label="特价"
                           align="center"
                           prop="special_price"
                           min-width="100px">
            <template slot-scope="{row}">
              <span>{{ row.special_price / 100 }}</span>
            </template>
          </el-table-column>
       

          <el-table-column label="状态"
                           prop="status"
                           class-name="status-col"
                           sortable="custom"
                           width="100">
            <template slot-scope="{row}">
              <!--  <el-tag :type="row.status | statusFilter">
            {{ row.status }}
          </el-tag> -->
              <span v-if="row.status==0"
                    class="status-ball draft" />
              <span v-if="row.status==1"
                    class="status-ball published" />
              <span>{{row.status | statusFilter}}</span>
              <!-- <span>{{ row.status }}</span> -->
            </template>
          </el-table-column>
          <el-table-column label="操作"
                           align="center"
                           width="230"
                           class-name="small-padding fixed-width">
            <template slot-scope="{row,$index}">

              <el-button v-if="row.status!=1"
                         size="mini"
                         type="success"
                         icon="el-icon-check"
                         @click="handleModifyStatus(row,1)" />
             <!--  <el-button v-if="row.status!=0"
                         size="mini"
                         type="warning"
                         @click="handleModifyStatus(row,0)">
                下架
              </el-button> -->
              <el-button type="primary"
                         size="mini"
                         icon="el-icon-edit"
                         @click.stop="toProductDetail(row)" />
              <el-button v-if="row.status!=1"
                         size="mini"
                         type="danger"
                         icon="el-icon-delete"
                         @click="handleDelete(row,$index)" />
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total>0"
                    :total="total"
                    :page.sync="listQuery.page"
                    :limit.sync="listQuery.page_size"
                    @pagination="getList" />

      </el-tab-pane>
    </el-tabs>

  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
// import {getProductList,getDatamap,putProductStatus,,setProductSort} from '@/api/product'
import {getProductList,putProductStatus,deleteProduct} from '@/api/hopeTravel/product'
import {getCountry,getCategory} from '@/api/hopeTravel/dataMap'
export default {
  name: 'ProductList',
  components: {Pagination},
  // directives: { waves },
  filters: {
    statusFilter(status) {
      switch (status) {
        case 0:
          return '已下架'
          break
        case 1:
          return '已上架'
          break
      }
    },
    /*  typeFilter(type) {
      return calendarTypeKeyValue[type]
    } */
  },
  data() {
    return {
      varities: [], // 类目数组
      brands: [], // 品牌数组
      countrys: [], // 国家数组
      activeName: 'sale', // tab选项卡
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        page_size: 10,
        category_id:'',
        country_id:'', 
        keyword:'',
        sort:'id',
        sort_type:'desc',
        status:1,
      },
      varityList:[],//接口返回的类目列表 作缓冲
      brandList:[],//接口返回的品牌列表 作缓冲
      countryList:[],//接口返回的国家列表 作缓冲
      // calendarTypeOptions,
      multipleSelectionSale: [], //保存销售中复选框数组
      multipleSelectionStore: [], //保存仓库中复选框数组

      multipleSelectionSaleStatus: false, //是否显示 销售中 批量下架
      multipleSelectionStoreStatus: false, //是否显示 仓库中 批量上架

      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create',
      },
      dialogPvVisible: false,

      downloadLoading: false,
      currentSort: '',//排序
    }
  },
  watch: {
    multipleSelectionSale(val) {
      if (val.length == 0) {
        this.multipleSelectionSaleStatus = false
      } else {
        this.multipleSelectionSaleStatus = true
      }
    },

    multipleSelectionStore(val) {
      if (val.length == 0) {
        this.multipleSelectionStoreStatus = false
      } else {
        this.multipleSelectionStoreStatus = true
      }
    },
  },
  created() {
    this.getList()
    this.getcountry()
    this.getcategory()
  },
  methods: {
    getcountry(){
      getCountry().then(res=>{
        if(res.code == 0){
          this.countryList = res.data;
        }
      })
    },
    getcategory(){
      getCategory({'status':1}).then(res=>{
        if(res.code == 0){
          this.varityList = res.data
        }
      })
    },
    toProductDetail(row){
      this.$router.push({ path: `/product/productManager/edit/${row.product_id}` })
    },
    //表格复选框选择 销售中
    toggleSelectionSale(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTableSale.toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleTableSale.clearSelection()
      }
    },
    handleSelectionChangeSale(val) {
      this.multipleSelectionSale = val
      // console.log(val);
    },
    //表格复选框选择 仓库中
    toggleSelectionStore(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTableStore.toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleTableStore.clearSelection()
      }
    },
    handleSelectionChangeStore(val) {
      this.multipleSelectionStore = val
    },
    //批量上架
    takeOnProduct(){
      console.log(this.multipleSelectionStore);
      let dataList = [];
      this.multipleSelectionStore.forEach((val,index)=>{
        dataList.push(val.product_id)
      })

      this.$confirm('是否批量上架产品?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {

          
            putProductStatus({"status":1,"data":dataList}).then(res=>{
        console.log(res);
        if(res.code == 0){
          this.$message({
                type: 'success',
                message: '批量上架产品成功!'
              });
          this.list= this.list.filter((val)=>{
             return !this.multipleSelectionStore.includes(val);
           })
          this.total = this.list.length;
        }
      })
          
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消上架'
          });          
      
    })

      
    },
    //批量下架
    takeOffProduct() {
      // console.log('批量下架')
     console.log(this.multipleSelectionSale);
      let dataList = [];
      this.multipleSelectionSale.forEach((val,index)=>{
        dataList.push(val.product_id)
      })

      this.$confirm('是否批量下架产品?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          putProductStatus({"status":0,"data":dataList}).then(res=>{
        console.log(res);
        if(res.code == 0){

          this.$message({
                type: 'success',
                message: '批量下架产品成功!'
              });

          this.list= this.list.filter((val)=>{
             return !this.multipleSelectionSale.includes(val);
           })
           console.log( this.list);
          this.total = this.list.length;
        }
      })
          
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消下架'
          });          
      
    })

      
    },
    // 点击切换tab选项卡
    handleClick(tab, event) {
      this.multipleSelectionSale = []
      this.multipleSelectionStore = []
      this.$refs.multipleTableSale.clearSelection()
      this.$refs.multipleTableStore.clearSelection()
      this.listQuery = {page: 1,
                        page_size: 20,}
      if(this.activeName=='sale'){
        this.listQuery.status = 1
        this.getList();
      }else{
        this.listQuery.status = 0
        this.getList();
      }
    },
    // 添加产品
    /* addProduct() {
      console.log('添加产品')
      this.$router.push({ path: '/product/pro' })
    }, */
    getList() {
      this.listLoading = true
      getProductList(this.listQuery).then(res => {
        if(res.code==0){
          this.total = res.total[0][`COUNT(*)`]
          this.list = res.data
        console.log(this.list)

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
        } 
      })
    },
    //搜索
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    //单个产品上下架
    handleModifyStatus(row, status) {
      /* this.$message({
        message: '操作Success',
        type: 'success',
      }) */
      
      // console.log(row.product_id,status);
      let dataList = {
        
        "status":status,
        "data":[row.product_id],
      }
       this.$confirm('是否修改产品上下架状态?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          putProductStatus(dataList).then(res=>{
        // console.log(res);
        if(res.code == 0){
          row.status = status
          console.log(row);
          
          if(status == 1){
            this.$message({
                type: 'success',
                message: '上架产品成功!'
              });
            this.list = this.list.filter(val=>{
              return row.product_id != val.product_id
            })
            this.total = this.list.length;
          }
          else{
            this.$message({
                type: 'success',
                message: '下架产品成功!'
              });
              this.list = this.list.filter(val=>{
              return row.product_id != val.product_id
            })
            this.total = this.list.length;
          }
          console.log(this.list);
          
        }
      })
          
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消修改产品上下架状态'
          });          
      
    })
      
    },
    //排序 
    sortChange(data) {
      console.log(data);
      const {prop, order} = data
      
      
      if (prop == 'product_id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      this.listQuery.sort = 'id'
      if (order == 'ascending') {
        this.listQuery.sort_type = 'asc'
      } else {
        this.listQuery.sort_type = 'desc'
      }
      console.log(this.listQuery);
      
      this.handleFilter()
    },
    /* sortByStatus(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+status'
      } else {
        this.listQuery.sort = '-status'
      }
      this.handleFilter()
    }, */
    handleDelete(row,$index){
      this.$confirm('是否删除下架产品?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteProduct(row.product_id).then(res=>{
            console.log(res);
            if(res.code == 0){

              this.$message({
                type: 'success',
                message: '删除产品成功!'
              });

              this.list = this.list.filter(val=>{
                  return row.product_id != val.product_id
                })
                this.total = this.list.length;
            }
            
          })
          
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
      
    })
    },
    //保存当前聚焦的排序值->供watch使用
    saveCurrentSort(e) {
      this.currentSort = e.target.value
    },
    //修改排序
    changeSort(e, row) {
      console.log(e)
      if (!e.target.value.trim()) {
        this.$set(row, 'sort', this.currentSort)
        return
      }
      if (this.currentSort == e.target.value) return
      setProductSort( { "product_id":row.product_id,"sort": parseInt(e.target.value)}).then(res => {
        this.$notify({
          message: '排序修改成功',
          type: 'success',
          duration: 2000,
        })
        this.getList()
      })
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    },
  },
}
</script>
<style scoped>
.status-ball {
  display: inline-block;
  border-radius: 50%;
  width: 8px;
  height: 8px;
}
.draft {
  background-color: #778899;
}
.published {
  background-color: #00ff00;
}
.add-brand {
  border: 2px solid #eee;
  padding: 10px 0 10px 15px;
}
img {
  width: 50px;
}
.input-new-sort {
  width: 80px;
  text-align: center;
}
.a-hover:hover{
    color: rgb(24, 144, 255);
  }
</style>
